package com.easygem.front.service.imp;

import com.easygem.common.error.SystemCodeEnum;
import com.easygem.common.error.SystemException;
import com.easygem.common.model.system.Dept;
import com.easygem.common.model.system.User;
import com.easygem.common.response.ActiveUser;
import com.easygem.common.utils.DepUtils;
import com.easygem.common.vo.front.SeatVO;
import com.easygem.front.mapper.DepartmentMapper;
import com.easygem.front.mapper.SeatMapper;
import com.easygem.front.mapper.ZoningMapper;
import com.easygem.front.service.ZoningService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qq240
 * @version 1.0
 * @className ZoningServiceImpl
 * @Description TODO
 * @date 2025/4/17 16:44
 */
@Service
public class ZoningServiceImpl implements ZoningService {
    @Autowired
    private ZoningMapper zoningMapper;
    @Autowired
    private SeatMapper seatMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    /**
     * 开启分区制
     *
     * @return
     */
    @Override
    public Integer openZoning(User user) {
        //查询可用坐席数，如果已经有了可用坐席数记录则不进行下列操作
//        List<Dept> isUpdate= selectAvailableSeatsNum(user.getDeptId());
//        if (isUpdate==null){
            //查询坐席数
            Integer availableSeatsNum = seatMapper.getMaxSeatsCount(user.getAccountName());
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("availableSeatsNum", availableSeatsNum);
            params.put("deptId", user.getDeptId());
            //更新根部门下当前可用的坐席数
            updateAvailableSeatsNum(params);
//        }
        return zoningMapper.openZoning(user.getAccountName());
    }

    /**
     * 关闭分区制
     *
     * @return
     */
    @Override
    public Integer closeZoning(User user) {
        return zoningMapper.closeZoning(user.getAccountName());
    }

    /**
     * 查询是否开启了分区制
     *
     * @param accountName
     * @return
     */
    @Override
    public Integer isZoning(String accountName) {
        return zoningMapper.isZoning(accountName);
    }

    /**
     * 查询次级部门
     *
     * @param deptId 根部门
     * @return
     */
    @Override
    public Dept selectSubDept(Long deptId) {
        return zoningMapper.selectSubDept(deptId);
    }

    /**
     * 更新分配可用坐席数后的部门
     *
     * @param map
     * @return
     */
    @Override
    public Integer updateSubDepts(Map<String, Object> map) {
        return zoningMapper.updateSubDepts(map);
    }

    /**
     * 更新可用坐席数
     *
     * @param map
     * @return
     */
    @Override
    public Integer updateAvailableSeatsNum(Map<String, Object> map) {
        return zoningMapper.updateAvailableSeatsNum(map);
    }

    /**
     * 查询可用坐席数
     *
     * @param deptId
     * @return
     */
    @Override
    public Integer selectAvailableSeatsNum(Long deptId) {
        Dept dept = selectSubDept(deptId);
        return zoningMapper.selectAvailableSeatsNum(dept.getSubDeptId());
    }

    /**
     * 更新跟部门的次级部门Id
     *
     * @param deptId 根部门Id
     * @return 更新结果
     */
    @Override
    public Integer updateAdminDeptIdByDeptId(Long deptId) {
        return zoningMapper.updateAdminDeptIdByDeptId(deptId);
    }

    /**
     * 更新部门的次级部门Id
     *
     * @param deptId 根部门Id
     * @return 更新结果
     */
    @Override
    public Integer updateSubDeptIdByDeptId(Long deptId) {
        return zoningMapper.updateSubDeptIdByDeptId(deptId);
    }

    /**
     * 清空部门的次级部门Id
     *
     * @param deptId 根部门Id
     * @return 更新结果
     */
    @Override
    public Integer cleanSubDeptIdByDeptId(Long deptId) {
        return  zoningMapper.cleanSubDeptIdByDeptId(deptId);
    }

    /**
     * 查询二级部门的信息
     *
     * @param deptId 根部门Id
     * @return 二级部门集合
     */
    @Override
    public List<Dept> getVFPDeptInfo(Long deptId) {
        return zoningMapper.getVFPDeptInfo(deptId);
    }

    /**
     * 查询一级部门的坐席数
     *
     * @param deptId 根部门Id
     * @return 二级部门集合
     */
    @Override
    public Integer getAdminSeatsNum(Long deptId) {
        return zoningMapper.getAdminSeatsNum(deptId);
    }

    /**
     * 更新部门的可用坐席数
     *
     * @param dept 部门信息
     * @return 更新结果
     */
    @Transactional
    @Override
    public String updateAllotSeatsByList(List<Dept> dept) {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        //提醒信息
        String msg = "";
        for (Dept item: dept) {
            if (item.getAvailableSeatsNum() != item.getAvailableSeatsNumOld()) {
                Integer zoningUsingSeatsCount = getZoningUsingSeatsCount(item.getDeptId(), activeUser.getUser().getAccountName());
                if (zoningUsingSeatsCount<=item.getAvailableSeatsNum()){
                    zoningMapper.updateAllotSeats(item);
                }else {
                    msg+=(item.getDeptName()+"部门分配坐席名额异常:该部门下已经开启"+zoningUsingSeatsCount+"个外呼坐席，期望分配名额："+item.getAvailableSeatsNum()+"个，小于已开启外呼坐席数。");
                }
            }
        }
        return msg;
    }
    /**
     * 得到当前已设置的坐席数量与最大坐席数量(分区制版)
     *
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public Map<String, Object> selectZoningSeatsCount(String accountName) {
        User selectAdminUser=zoningMapper.selectAdminUser(accountName);
        Map<String, Object> seatsCount=new HashMap<>();
        seatsCount.put("availableSeatsNum",selectAvailableSeatsNum(selectAdminUser.getDeptId()));
        seatsCount.put("useSeatsNumbers",getZoningUsingSeatsCount(selectSubDept(selectAdminUser.getDeptId()).getSubDeptId(),selectAdminUser.getAccountName()));
        //当超级管理员操作坐席设置时额外查询出空余可用坐席数
        if (selectAdminUser.getType()==0){
            Integer availableSeatsNumTotal=0;
            List<Dept> subDepts=getVFPDeptInfo(selectAdminUser.getDeptId());
            for (Dept dept : subDepts){
                availableSeatsNumTotal+=dept.getAvailableSeatsNum();
            }
            Integer openSeatsNumTotal=zoningMapper.getOpenSeatNumsById(selectAdminUser.getDeptId());
            Integer freeAvailableSeatsNum=Integer.parseInt(String.valueOf(seatsCount.get("availableSeatsNum")))-(availableSeatsNumTotal+openSeatsNumTotal);
            seatsCount.put("freeAvailableSeatsNum",freeAvailableSeatsNum);
        }
        List<Dept> vfpDeptInfo = getVFPDeptInfo(selectAdminUser.getDeptId());
        Integer ofAssignedSeatsNum =0;
        for (Dept dept: vfpDeptInfo) {
            ofAssignedSeatsNum+=dept.getAvailableSeatsNum();
        }
        seatsCount.put("ofAssignedSeatsNum",ofAssignedSeatsNum);
        System.out.println(seatsCount);
        return seatsCount;
    }
    /**
     * 更新坐席状态(分区制版)
     * @param seatVO
     * @return
     * @throws SystemException
     */
    @Override
    public Integer setZoningSeatStatus(SeatVO seatVO) throws SystemException {
        User user = seatMapper.selectByPrimaryKey(seatVO.getUserId());
        if (user == null) {
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR);
        }else {
            if (user.getStatus()==-1||user.getStatus()==-2){
                throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"该用户无法更改状态");
            }
        }
        User selectAdminUser=zoningMapper.selectAdminUser(user.getAccountName());
        Map<String,Object> map=new HashMap<>();
        map.put("availableSeatsNum",selectAvailableSeatsNum(user.getDeptId()));
        //当操作的用户与超级管理员是同一个部门时
        if (selectAdminUser.getType()==0&&user.getStatus()==0){
            if (selectAdminUser.getDeptId().equals(user.getDeptId())){
                Integer availableSeatsNumTotal=0;
                List<Dept> subDepts=getVFPDeptInfo(selectAdminUser.getDeptId());
                for (Dept dept : subDepts){
                    availableSeatsNumTotal+=dept.getAvailableSeatsNum();
                }
                Integer openSeatsNumTotal=zoningMapper.getOpenSeatNumsById(selectAdminUser.getDeptId());

                if (Integer.parseInt(String.valueOf(map.get("availableSeatsNum")))<=((availableSeatsNumTotal+openSeatsNumTotal))){
                    throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"空余可用坐席数已不足"+
                            "操作中断处的坐席为："+user.getUserName());
                }
            }
        }


        map.put("useSeatsNumbers",getZoningUsingSeatsCount(selectSubDept(user.getDeptId()).getSubDeptId(),user.getAccountName()));

        if (map.get("availableSeatsNum")!=null){
            //判断是否为开启坐席操作
            if(seatVO.getStatus()==1){
                Integer maxSeatsNumbers=Integer.parseInt(String.valueOf(map.get("availableSeatsNum")));
                Integer useSeatsNumbers=Integer.parseInt(String.valueOf(map.get("useSeatsNumbers")));
                System.out.println("可用数+使用已使用数:"+maxSeatsNumbers+":"+useSeatsNumbers);
                if (useSeatsNumbers.equals(maxSeatsNumbers)||useSeatsNumbers>maxSeatsNumbers){
                    throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"坐席数量已达最大值" +
                            "\n该部门可用坐席数为："+maxSeatsNumbers+
                            "\n你要开启的坐席为："+user.getUserName());
                }
            }
        }
        BeanUtils.copyProperties(seatVO, user);
        return seatMapper.updateByPrimaryKeySelective(user);
    }
    /**
     * 根据次级部门id得到其下所有已开启的坐席数量
     * @param deptId
     * @param accountName
     * @return
     */
    @Override
    public Integer getZoningUsingSeatsCount(Long deptId,String accountName) {
        System.out.println("部门id:"+deptId+";账户名:"+accountName);
        List<Long> deptIdList=DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(),deptId);
        Map<String,Object> map=new HashMap<>();
        map.put("deptIds",deptIdList);
        map.put("accountName",accountName);
        return zoningMapper.getZoningUsingSeatsCount(map);
    }

    /**
     * 重置根部门下的坐席
     * @param deptId 根部门id
     */
    @Override
    public void resetSeatsStatusByDeptId(Long deptId) {
        List<Long> deptIdList=DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(),deptId);
        zoningMapper.resetSeatsStatusByDeptIds(deptIdList);
    }

    /**
     * 根据账户名得到超级管理员用户
     * @param accountName
     * @return
     */
    @Override
    public User selectAdminUser(String accountName) {
        return zoningMapper.selectAdminUser(accountName);
    }
}
